package deyi.udp;

import deyi.utils.AppConfig;
import deyi.utils.SpringContextUtil;
import lombok.*;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Component("udpserver")
@Data
@NoArgsConstructor
public class UdpServer {

    @Value(value = "${localUdpRevPort}")
    private int port;
    private NioDatagramAcceptor acceptor;

    @PostConstruct
    public void initUdpServer() throws Exception{
        acceptor = new NioDatagramAcceptor();
        acceptor.setHandler(new UdpEventHandle());
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        DatagramSessionConfig dcfg = acceptor.getSessionConfig();
        dcfg.setReuseAddress(true);
        acceptor.bind(new InetSocketAddress(port));
        System.out.println("udp server start .....port:" + port);
    }

    @PreDestroy
    public void stopServer(){
        acceptor.unbind();
    }
}
